package org.jeecg.modules.online.cgform.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecgframework.poi.handler.impl.ExcelDataHandlerDefaultImpl;
import org.jeecgframework.poi.util.PoiPublicUtil;

public class CgFormExcelHandler extends ExcelDataHandlerDefaultImpl {

	Map<String, OnlCgformField> fieldMap;

	ISysBaseAPI sysBaseAPI;

	/**
	 * 若存本地文件，需磁盘目录
	 */
	String uploadBasePath;

	/**
	 * 业务路径 默认online
	 */
	String bizPath;

	/**
	 * 上传类型 local minio alioss
	 */
	String uploadType;

	/**
	 *
	 * @param lists 字段集合
	 * @param uploadBasePath 存储文件的磁盘目录
	 * @param uploadType 上传类型读取配置获得 local minio alioss
	 */
	public CgFormExcelHandler(List<OnlCgformField> lists,String uploadBasePath,String uploadType) {
		fieldMap = convertDate(lists);
		this.uploadBasePath=uploadBasePath;
		this.bizPath = "online";
		this.uploadType=uploadType;
		this.sysBaseAPI = SpringContextUtils.getBean(ISysBaseAPI.class);
	}

	private Map<String, OnlCgformField> convertDate(List<OnlCgformField> lists) {
		Map<String, OnlCgformField> maps = new HashMap<String, OnlCgformField>();

		for (OnlCgformField cgFormFieldEntity : lists) {
			maps.put(cgFormFieldEntity.getDbFieldTxt(), cgFormFieldEntity);
		}
		return maps;
	}


	@Override
	public void setMapValue(Map<String, Object> map, String originKey, Object value) {
		String realKey = getRealKey(originKey);
		if (value instanceof Double) {
			map.put(realKey, PoiPublicUtil.doubleToString((Double) value));
		} else if(value instanceof byte[]){
			byte[] arr = (byte[])value;
			String path = CgformUtil.uploadOnlineImage(arr, uploadBasePath, bizPath, uploadType);
			if(path!=null){
				map.put(realKey, path);
			}
		} else {
			map.put(realKey, value==null?"":value.toString());
		}
	}
	private String getRealKey(String originKey) {
		if (fieldMap.containsKey(originKey)) {
			//主表字段
			return "$mainTable$"+fieldMap.get(originKey).getDbFieldName();
		}
		//子表字段
		return "$subTable$"+originKey;
	}

}